# -*- coding: utf-8 -*-
from weibopy.auth import OAuthHandler
from weibopy.api import API
import webbrowser
from weibopy.error import WeibopError

APP_KEY = '1871371929'
APP_SECRET = '152b44b6d718af59b3314d22161ffac0'


#设定网页应用回调页面(桌面应用设定此变量为空)
BACK_URL = " "
#验证开发者密钥.
auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)

#获取授权页面网址.
auth_url = auth.get_authorization_url()

#取出请求令牌密钥(桌面应用跳过此处)
#rtKey = auth.request_token.key
#rtSecret = auth.request_token.secret

#设定请求令牌密钥(桌面应用跳过此句)
#auth.set_request_token(rtKey, rtSecret)

print 'Please authorize: ' + auth_url
webbrowser.open(auth_url)
verifier = raw_input('PIN: ').strip()

#获取用户令牌密钥.
access_token = auth.get_access_token(verifier)
atKey = access_token.key
atSecret = access_token.secret
print atKey, atSecret


#设定用户令牌密钥.
auth.setToken(atKey, atSecret)
#绑定用户验证信息.
api = API(auth)
try:
        user = api.verify_credentials()
except WeibopError, e:
        print e


#用户ID
userid = user.id
#用户昵称.
username = user.screen_name.encode('utf-8')

print userid, username

#这里人工输入或者自动获取ImagePath
ImagePath = None

#如果不传送图片.
if (ImagePath == None):
  #发布普通微博.
  try:
    #message为微博消息，lat为纬度，long为经度.
    message = '元宝电商测试Python微博客户端'
    lat = 344
    long = 3356
    api.update_status(message, lat, long)
  except WeibopError, e:
    return e.reason

#如果传送图片.
else:
  #发布图文微博.
    try:
      #ImagePath为图片在操作系统中的访问地址，其余同上.
        api.upload(ImagePath, message, lat, long)
    except WeibopError, e:
        return e.reason
